package com.songqi.common.core.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * @description:
 * @author: songqi(13776346982)
 * @date: 2024/6/4 09:25
 */
public class NumberRegexValidator implements ConstraintValidator<NumberRegex, Double> {

    private String regex = "";

    @Override
    public void initialize(NumberRegex constraintAnnotation) {
        regex = constraintAnnotation.regex();;
    }

    @Override
    public boolean isValid(Double number, ConstraintValidatorContext constraintValidatorContext) {
        if (number == null) {
            return true;
        }
        // 将 Double 转换为 String
        String numberStr = number.toString();
        Pattern pattern = Pattern.compile(regex);
        // 使用正则表达式验证格式
        return pattern.matcher(numberStr).matches();
    }
}
